package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.controller
 */
@RestController
@Slf4j
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /**
     * 上传文件 upload.html
     * @param username
     * @param age
     * @param file
     * @return
     */
    /*@PostMapping("upload")
    public Result upload(String username, Integer age, MultipartFile file) throws IOException {
        log.info("username={}, age={}", username,age);
        //1. 生成唯一 的文件名, originalFilename原文件名
        String originalFilename = file.getOriginalFilename();
        // 截取文件扩展名,abc.jpg
        // ext = .jpg
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + ext;
        //2. 保存到本地磁盘上
        file.transferTo(new File("D:/upload/" + newFilename));
        return Result.success();
    }*/

    /**
     * 上传文件，上传给阿里OSS存储
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public Result upload(MultipartFile file) {
        try {
            String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            return Result.success(url);
        } catch (Exception e) {
            log.error("上传文件到阿里云OSS失败", e);
            return Result.error("上传文件失败");
        }
    }
}
